import axios from 'axios';
import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Notify } from 'react-vant'
const Index: React.FC = () => {
  const { state } = useLocation();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate()
  const payNow = () => {
    axios.get('/api/pay', { params: state }).then(resp => {
      const { code, data, error } = resp.data
      if (code === 200) {
        globalThis.open(data);
        // 轮训 查询结果
        setLoading(true)
        query()
      } else {
        console.log(error)
      }
    })
  }

  const query = () => {
    setLoading(true)
    const timer = setInterval(async () => {
      const resp = await axios.get('/api/pay/query', { params: { id: state.id } })
      const { code, tradeStatus } = resp.data.data;

      if (code === '10000') {
        switch (tradeStatus) {
          case 'WAIT_BUYER_PAY':
            Notify.show({ type: 'success', message: '交易创建，等待买家付款' })
            break;
          case 'TRADE_CLOSED':
            Notify.show({ type: 'success', message: '未付款交易超时关闭，或支付完成后全额退款' })
            clearInterval(timer)
            break;
          case 'TRADE_SUCCESS':
            Notify.show({ type: 'success', message: '交易支付成功' });
            clearInterval(timer)
            navigate('/pay/result')
            break;
          case 'TRADE_FINISHED':
            Notify.show({ type: 'success', message: '交易结束，不可退款' })
            clearInterval(timer)
            break;
        }
      }
    }, 1000);

  }

  return (
    <div>
      <div>ID： {state.id}</div>
      <div>price: {state.price}</div>
      <div>title:  {state.title}</div>
      <button onClick={() => payNow()}>立即付款</button>

      {
        loading && <div className='loading' >
          查询支付结果中...
        </div>
      }
    </div>
  )
}

export default Index
// out_trade_no